package common.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {
    private static HttpURLConnection Send(String uri, String mehtod, String data, Map<String, String> headers) throws Exception {
        URL url = new URL(uri);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod(mehtod);
        System.out.println("Http " + mehtod + " " + uri);

        if (headers != null)
            for (Map.Entry<String, String> header : headers.entrySet())
                http.setRequestProperty(header.getKey(), header.getValue());

        http.connect();
        System.out.println("Http response code " + http.getResponseCode());

        System.out.println();
        return http;
    }

    public static HttpURLConnection Get(String uri, Map<String, String> headers) throws Exception {
        return Send(uri, "GET", null, headers);
    }

    public static HttpURLConnection Get(String url) throws Exception {
        return Get(url, null);
    }

    public static HttpURLConnection Post(String uri, String data, Map<String, String> headers) throws Exception {
        return Send(uri, "POST", data, headers);
    }

    public static HttpURLConnection Post(String url, String data) throws Exception {
        return Post(url, data, null);
    }

    public static String GetString(String uri, Map<String, String> headers) throws Exception {
        HttpURLConnection http = Get(uri, headers);
        //String result = BinaryUtil.GetText(http.getInputStream());
        String result = http.getResponseMessage();
        http.disconnect();
        return result;
    }

    public static String GetString(String url) throws Exception {
        return GetString(url, null);
    }

    public static void Download(String uri, String path, Map<String, String> headers) throws Exception {
        HttpURLConnection http = Get(uri, headers);
        System.out.println("Downloaded size " + http.getContentLength());
        System.out.println("Try to save to " + path);
        FileUtil.save(path, http.getInputStream());
        http.disconnect();
        System.out.println();
    }

    public static void Download(String url, String path) throws Exception {
        Download(url, path, null);
    }

    public static String PostJson(String url, String json) throws Exception {
        StringStringMap headers = new StringStringMap("Content-Type", "application/json");
        HttpURLConnection http = Post(url, json, headers);
        //String result = BinaryUtil.GetText(http.getInputStream());
        String result = http.getResponseMessage();
        http.disconnect();
        return result;
    }
}
